import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_todo_2019/common/application.dart';
import 'package:flutter_todo_2019/common/common.dart';
import 'package:flutter_todo_2019/event/mine_msg_count_event_new.dart';
import 'package:flutter_todo_2019/page/api/apis_service.dart';
import 'package:flutter_todo_2019/page/mode/todo_list_model.dart';
import 'package:flutter_todo_2019/page/utils/GlobalInfo.dart';
import 'package:flutter_todo_2019/page/utils/sp_util.dart';
import 'package:flutter_todo_2019/page/utils/toast_util.dart';
import 'package:flutter_todo_2019/widgets/item_todo_list.dart';

class TestHomePage extends StatefulWidget {
  @override
  _TestHomePageState createState() => _TestHomePageState();
}

class _TestHomePageState extends State<TestHomePage> with SingleTickerProviderStateMixin {
  ScrollController _scrollViewController;
  TabController _tabController;
  int todoType = 0;
  Map<String, List<TodoBean>> map = Map();

  final SlidableController slidableController = SlidableController();

  int _page = 1;
  List<TodoBean> _todoBeanList = new List();
  @override
  void initState() {
    super.initState();
    _scrollViewController = ScrollController(initialScrollOffset: 0.0);
    _tabController = TabController(vsync: this, length: 3);
    getNoTodoList();
  }

  @override
  void dispose() {
    super.dispose();
    _scrollViewController.dispose();
    _tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: ThemeData(primaryColor: Colors.white),
      child: Scaffold(
          appBar: AppBar(
            elevation: 1.0,
            title: Text("首页"),
          ),
          body: NestedScrollView(
              controller: _scrollViewController,
              headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
                return <Widget>[
                  SliverAppBar(
                    pinned: true,
                    floating: true,
                    expandedHeight: 280,
                    flexibleSpace: FlexibleSpaceBar(
                      collapseMode: CollapseMode.pin,
                      background: Container(//头部整个背景颜色
                        height: double.infinity,
                        color: Color(0xffcccccc),
                        child: Column(
                          children: <Widget>[
                            _buildBanner(),
                            _buildButtons(),
                            _buildTabBarBg()
                          ],
                        ),
                      ),
                    ),
                    bottom: TabBar(controller: _tabController, tabs: [
                      Tab(text: "aaa"),
                      Tab(text: "bbb"),
                      Tab(text: "ccc"),
                    ]),
                  )
                ];
              },
              body: TabBarView(controller: _tabController, children: [
                _buildListView("aaa:"),
                _buildListView("bbb:"),
                _buildListView("ccc:"),
              ]))),
    );
  }

  Widget _buildBanner() {
    return Container(
      margin: EdgeInsets.only(left: 16.0, right: 16.0, top: 12.0),
      height: 144,
      child: Swiper(//第三方的banner库：flutter_swiper
          itemBuilder: (BuildContext context, int index) {
            return Container(
              width: double.infinity,
              height: 144,
              child: Image.network(
                "https://github.com/best-flutter/flutter_swiper/raw/master/banner.jpg",
                height: double.infinity,
                fit: BoxFit.fill,
              ),
            );
          },
          itemCount: 3,
          scale: 0.9,
          pagination: new SwiperPagination()),
    );
  }

  //banner下面的按钮
  Widget _buildButtons() {
    return Expanded(
      child: Row(
        children: <Widget>[
          _buildButtonItem(Icons.chat, "xxxx"),
          Image.asset("assets/images/phone_flow_chart_arrow.png", height: 8),
          _buildButtonItem(Icons.pages, "xxxx"),
          Image.asset("assets/images/phone_flow_chart_arrow.png", height: 8),
          _buildButtonItem(Icons.phone_android, "xxxx"),
          Image.asset("assets/images/phone_flow_chart_arrow.png", height: 8),
          _buildButtonItem(Icons.print, "xxxx"),
        ],
      ),
    );
  }

  Widget _buildButtonItem(IconData icon, String text) {
    return Expanded(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Icon(icon, size: 28.0),
            Container(
              margin: EdgeInsets.only(top: 8.0),
              child: Text(text, style: TextStyle(color: Color(0xff999999), fontSize: 12)),
            )
          ],
        ));
  }

  Widget _buildTabBarBg() {
    return Container(  //TabBar圆角背景颜色
      height: 50,
      child: ClipRRect(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(15), topRight: Radius.circular(15)),
          child: Container(color: Colors.white)),
    );
  }

  Widget _buildListView(String s){
    return  ListView.builder(
      itemBuilder: itemView,
      physics: AlwaysScrollableScrollPhysics(),
      shrinkWrap: true,
      itemCount: _todoBeanList.length,
    );
  }
  Widget itemView(BuildContext context, int index) {
    TodoBean item = _todoBeanList[index];
    bool isShowSuspension = false;
    if (map.containsKey(item.dateStr)) {
      if (map[item.dateStr].length > 0) {
        if (map[item.dateStr][0].id == item.id) {
          isShowSuspension = true;
        }
      }
    }
    return ItemTodoList(
      isTodo: true,
      item: item,
      slidableController: slidableController,
      isShowSuspension: isShowSuspension,
      todoType: todoType,
    );
  }
  /// 获取待办TODO列表数据
  Future getNoTodoList() async {
    _page = 1;
    apiService.getNoTodoList((TodoListModel model) {
      if (model.errorCode == Constants.STATUS_SUCCESS) {
        if (model.data.datas.length > 0) {
          setState(() {
            _todoBeanList.clear();
            _todoBeanList.addAll(model.data.datas);
          });
          rebuildData();
        }
      } else {
        T.show(msg: model.errorMsg);
      }
    }, (error) {
    }, todoType, _page);
  }

  /// 重新构建数据
  void rebuildData() {
    map.clear();
    Set<String> set = new Set();
    _todoBeanList.forEach((bean) {
      set.add(bean.dateStr);
    });

    set.forEach((s) {
      List<TodoBean> list = new List();
      map.putIfAbsent(s, () => list);
    });

    _todoBeanList.forEach((bean) {
      map[bean.dateStr].add(bean);
    });
    if (null != _todoBeanList && _todoBeanList.length > 0)
      //TODO 数据组装完毕
      SPUtil.putString(
          GlobalInfo.MSG_NOFINSH_COUNT, _todoBeanList.length.toString());
    Application.eventBus.fire(new CountMsgNewEvent());
  }


}